package com.yh.utils.extract.spring.listener;

import com.yh.utils.extract.config.DynamicDatasource;
import com.yh.utils.extract.jdbcTemplet.CreateHandler;
import com.yh.utils.extract.model.DataSourceDO;
import com.yh.utils.extract.service.DataSourceService;
import com.yh.utils.extract.spring.event.RdcStartEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class DbInitListener implements ApplicationListener<RdcStartEvent> {

    @Autowired
    DataSourceService dataSourceService;

    @Autowired(required = false)
    DynamicDatasource dynamicDatasource;

    @Autowired
    private Environment env;

    @Autowired
    CreateHandler createHandler;

    @Override
    public void onApplicationEvent(RdcStartEvent event) {
        initTable();

        while (dynamicDatasource!=null){
            reflashDataSource();
        }
    }

    public void reflashDataSource() {
        try {
            dynamicDatasource.clearDataSource();
            Map<Object, Object> sources=new HashMap<>();
            List<DataSourceDO> list = dataSourceService.queryList();
            if(list!=null && list.size()>0){
                for(DataSourceDO dataSourceDO:list){
                    boolean dataSource = dynamicDatasource.createDataSource(dataSourceDO);
                    if(!dataSource){
                        log.info("初始化数据源{}失败",dataSourceDO.getName());
                    }else{
                        log.info("初始化数据源{}成功",dataSourceDO.getName());
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void  initTable(){
        createHandler.createTable();
    }

}
